from datetime import datetime
from typing import List

import strawberry
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker

engine = create_async_engine(
    "mysql+aiomysql://root:123456@localhost:3306/sqlmap?charset=utf8mb4",
    echo=True,
)

engine = create_async_engine("sqlite+aiosqlite:///graphql.sqlite")

async_session = sessionmaker(
    engine, expire_on_commit=True, class_=AsyncSession
)

session = async_session()


# 查询模型
@strawberry.type
class User:
    id: int = strawberry.field(description='用户id')
    username: str = strawberry.field(description='用户名')


@strawberry.type
class Message:
    errmsg: str = 'ok'


# 输入参数模型
@strawberry.input
class AddUserInput:
    username: str = strawberry.field(description='用户名')
    password: str = strawberry.field(description='密码')


# resolver
async def resolver_get_user():
    """获取用户列表"""
    results = await session.execute('select id, username from user;')
    return [User(**dict(zip(result.keys(), result))) for result in results]


@strawberry.type
class Query:
    users: List[User] = strawberry.field(resolver=resolver_get_user)


@strawberry.type
class Mutation:

    @strawberry.field
    async def add_user(self, username: str, password: str) -> User:
        sql = 'insert into user (username, password) values ( "%s", "%s")' % (username, password)
        await session.execute(sql)
        await session.commit()
        sql = 'select id,username from user order by id desc limit 1'
        results = await session.execute(sql)
        return [User(**dict(zip(result.keys(), result))) for result in results][0]

    @strawberry.field
    async def add_user_input(self, user: AddUserInput) -> User:
        sql = 'insert into user (username, password) values ( "%s", "%s")' % (user.username, user.password)
        await session.execute(sql)
        await session.commit()
        sql = 'select id,username from user order by id desc limit 1'
        results = await session.execute(sql)
        return [User(**dict(zip(result.keys(), result))) for result in results][0]

    @strawberry.field
    async def del_user(self, id: int) -> Message:
        sql = f'delete from user where id={id}'
        await session.execute(sql)
        return Message()


schema = strawberry.Schema(query=Query, mutation=Mutation)


# strawberry server schema
